﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Common;
using Zocono.WCS.Admin.Models.Comm;
using Zocono.WCS.Admin.Models.Module;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Application.AppUserManage;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoUser;

namespace Zocono.WCS.Admin.Controllers
{
    public class HomeController : BaseController
    {

        private readonly UserApp _userApp;

        public HomeController(UserApp userApp, TracesApp tracesApp, IMemoryCache memoryCache, IHttpContextAccessor httpContextAccessor) : base(memoryCache, tracesApp, httpContextAccessor)
        {
            _userApp = userApp;
        }

        [BasicAuth]
        public async Task<IActionResult> Index()
        {
            var user = GetUserModel();
            if (user != null)
            {
                var list = await _userApp.GetRoleFunctionByRoleId(user.RoleId);
                if (list != null)
                {
                    var pList = new List<ModulePage>();
                    ModulePage module;
                    Children children;
                    foreach (var info in list) //处理菜单信息
                    {
                        if (info.PId == 0)
                        {
                            module = new ModulePage();
                            module.id = info.FunctionID.ToString();
                            module.name = info.FullName;
                            module.icon = info.MenuIcon;
                            pList.Add(module);
                        }
                        if (info.PId > 0)
                        {
                            module = pList.Find(i => i.id.ToInt64() == info.PId);
                            if (module != null)
                            {
                                if (module.children == null)
                                    module.children = new List<Children>();
                                children = new Children();
                                children.id = info.FunctionID.ToString();
                                children.name = info.FullName;
                                children.url = info.Url;
                                module.children.Add(children);
                            }
                        }
                    }
                    user.Modules = pList;
                }
            }

            return View(user);
        }
        /// <summary>
        /// 用户登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UserLoginAsync()
        {
            string errMsg;
            string userId = Request.Form["userId"];
            string userPwd = Request.Form["userPwd"];
            string online = Request.Form["online"].ToString();
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(userPwd))
            {
                errMsg = "用户名不能为空";
            }
            else
            {
                try
                {
                    var user = await _userApp.LoginAsync(userId, userPwd);
                    if (user != null)
                    {
                        var userModel = new UserModel();
                        userModel.UserName = user.UserName;
                        userModel.UserID = user.UserID;
                        userModel.FullName = user.FullName;
                        userModel.Department = user.Department;
                        userModel.RoleName = "";
                        userModel.RoleId = user.RoleID;
                        userModel.RandomId = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(10, 99);
                        var token = DesHelper.EncryptDES(JsonUtils.Serialize(userModel));
                        var time = online == "on" ? 1200 : 30;
                        SetCookies("User_Token", token, time);
                        //await AddTracesInfo(1, 0, "用户登录");
                        return CreateJsonGetResult(true);
                    }
                    else
                        errMsg = "用户名或密码错误";
                }
                catch (Exception e)
                {
                    errMsg = e.Message;
                }
            }
            return CreateJsonGetResult(false, errMsg);
        }

        /// <summary>
        /// 用户刷卡登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UserLoginByIcAsync()
        {
            string errMsg;
            
            string code = Request.Form["ic"].ToString();
            if (string.IsNullOrEmpty(code))
            {
                errMsg = "用户ic卡号不能为空";
            }
            else
            {
                try
                {
                    var user = await _userApp.LoginByIcAsync(code);
                    if (user != null)
                    {
                        var userModel = new UserModel();
                        userModel.UserName = user.UserName;
                        userModel.UserID = user.UserID;
                        userModel.FullName = user.FullName;
                        userModel.Department = user.Department;
                        userModel.RoleName = "";
                        userModel.RoleId = user.RoleID;
                        userModel.RandomId = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(10, 99);
                        var token = DesHelper.EncryptDES(JsonUtils.Serialize(userModel));
                        var time = 60;
                        SetCookies("User_Token", token, time);
                        //await AddTracesInfo(1, 0, "用户登录");
                        return CreateJsonGetResult(true);
                    }
                    else
                        errMsg = "用户不存在或未录入ic卡号";
                }
                catch (Exception e)
                {
                    errMsg = e.Message;
                }
            }
            return CreateJsonGetResult(false, errMsg);
        }
        /// <summary>
        /// 获取用户菜单信息
        /// </summary>
        /// <returns></returns>
        [BasicAuth]
        public async Task<JsonResult> GetUserMenuAsync()
        {
            var user = GetUserModel();
            if (user == null)
                return CreateJsonGetResult(false);
            var list = await _userApp.GetRoleFunctionByRoleId(user.RoleId);
            if (list != null)
            {
                var pList = new List<ModulePage>();
                ModulePage module;
                Children children;
                foreach (var info in list) //处理菜单信息
                {
                    if (info.PId == 0)
                    {
                        module = new ModulePage();
                        module.id = info.ID.ToString();
                        module.name = info.FullName;
                        module.icon = info.MenuIcon;
                        pList.Add(module);
                    }
                    if (info.PId > 0)
                    {
                        module = pList.Find(i => i.id.ToInt64() == info.PId);
                        if (module != null)
                        {
                            if (module.children == null)
                                module.children = new List<Children>();
                            children = new Children();
                            children.id = info.ID.ToString();
                            children.name = info.FullName;
                            children.url = info.Url;
                            module.children.Add(children);
                        }
                    }
                }
                return CreateJsonGetResult(true, "成功", pList);
            }
            return CreateJsonGetResult(false);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public JsonResult QuitLogin()
        {
            DeleteCookies("User_Token");
            return CreateJsonGetResult(true);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [BasicAuth]
        public async Task<JsonResult> UpdateUserPwdAsync()
        {
            string pwd = Request.Form["pwd"].ToString();
            string oldPWD = Request.Form["oldpwd"].ToString();
            var user = GetUserModel();
            bool result;
            var mes = "失败";
            try
            {
                result = await _userApp.UpdatePasswordAsync(user.UserID, pwd, oldPWD);
                if (result) mes = "成功";
            }
            catch (Exception e)
            {
                result = false;
                mes = e.Message;
            }
            await AddTracesInfo(3, 0, "修改密码");
            return CreateJsonGetResult(result, mes);
        }


        [BasicAuth]
        public async Task<IActionResult> UserInfoAsync()
        {
            var user = GetUserModel();
            var query = new QueryUserDto();
            query.UserName = user.UserName;
            var list = await _userApp.GetUserListAsync(query);
            var dto = new UserInfoDto();
            if (list != null && list.Count > 0)
                dto = list[0];
            await AddTracesInfo(5, 0, "获取用户信息");
            return View(dto);
        }

        public IActionResult Welcome()
        {

            return View();
        }

    }
}
